package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderFeignService orderFeignService;
    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1.判断如果还没有这个库存记录，那就是新增操作
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities==null || entities.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字,如果失败，整个事务不需要回滚
            //远程查询sku的名字
            //处理异常的两种办法
            //1.自已去catch
            //todo 还可以用什么办法让异常出现后不会滚
            try {
                R info = productFeignService.info(skuId);
                Map data = (Map<String,Object>)info.get("skuInfo");
                if (info.getCode()==0){
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }

            wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku的总库存量
            Long count=baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 为某个订单锁定库存
     *  @Transactional:默认只要是有运行时异常都会回滚
     * @param itemVos
     * @return
     * 库存解锁的场景
     * 1). 下订单成功，订单过期没有支付被系统自动取消，被用户手动取消，都要解锁库存
     *
     * 2). 下订单成功库存锁定成功，接下来的业务调用失败，导致订单回滚
     *      之前锁定的库存就要自动解锁
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo itemVos) {

        /**
         * 保存库存工作单的详情  -->追溯
         */

        // 锁库存之前先保存订单 以便后来消息撤回
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(itemVos.getOrderSn());
        orderTaskService.save(taskEntity);



        //1.商品的信息
        List<OrderItemVo> locks = itemVos.getLocks();
        List<SkuWareHasStock> wareList = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(item.getSkuId());
            //查询这个商品在哪里有库存
            List<Long> wareId = wareSkuDao.listWareIdHasstcok(item.getSkuId());
            skuWareHasStock.setWareId(wareId);
            skuWareHasStock.setNum(item.getCount());
            return skuWareHasStock;
        }).collect(Collectors.toList());

        //2.锁定库存

        for (SkuWareHasStock skuWareHasStock : wareList) {
            Boolean skuStock=false;
            long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareId();
            Integer num = skuWareHasStock.getNum();
            if (wareIds==null || wareIds.size()==0){
                //没有一个仓库有这个商品
                throw new NoStockException(skuId);
            }

            // 1 如果每一个商品都锁定成功 将当前商品锁定了几件的工作单记录发送给MQ
            // 2 如果锁定失败 前面保存的工作单信息回滚了(发送了消息却回滚库存的情况，没关系，用数据库id查就可以)
            for (Long wareId : wareIds) {
                //成功返回的就是1 否则为0
                Long count= wareSkuDao.lockSkuStock(skuId,wareId,num);
                if (count==1){
                    //当前仓库锁成功
                    skuStock=true;
                    //TODO  告诉MQ库存锁定成功 一个订单锁定成功 消息队列就会有一个消息
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "华为", skuWareHasStock.getNum()
                            , taskEntity.getId(), wareId, 1);
                    // db保存订单sku项工作单详情，告诉商品锁的哪个库存
                    orderTaskDetailService.save(entity);
                    // 发送库存锁定消息到延迟队列
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity, detailTo);
                    // 防止回滚以后找不到数据
                    lockedTo.setDetail(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked",
                            lockedTo);
                    break;
                }else {
                    //当前仓库锁失败，库存量不足,尝试下一个仓库
                }
            }
            if (skuStock==false){
                //商品库存没有被锁住，库存不足
                throw new NoStockException(skuId);
            }
        }
        //3.到这一步就是锁定成功了
        return true;
    }


    //@RabbitListener 可以标注在类上面，需配合 @RabbitHandler 注解一起使用

    /**
     *  只要解锁库存的消息失败，一定要告诉服务失败，不要删除消息，重试解锁
     * @param to
     * @param
     */
    @Override
    public void unlockStock(StockLockedTo to) {
        System.out.println("收到解锁库存的消息");
        // 库存id
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        /**
         * 解锁库存
         * 	查询数据库关系这个订单的详情
         * 		有: 证明库存锁定成功
         * 			1.没有这个订单, 必须解锁
         * 			2.有这个订单 不是解锁库存
         * 				订单状态：已取消,解锁库存
         * 				没取消：不能解锁	;
         * 		没有：就是库存锁定失败， 库存回滚了 这种情况无需回滚
         */
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if(byId != null) {
            // 解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();//根据订单号查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode()==0){
                //订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data==null||data.getStatus()==4){
                    //订单不存在-->解锁库存
                    // 订单已取消 状态1 已锁定  这样才可以解锁
                    if(byId.getLockStatus() == 1){
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                        // 手动确认消息消费，回复给队列 ,删除信息 false:批量
                    }
                }
            }else {
                // 消息拒绝 重新放回队列 让别人继续消费解锁
                throw new RuntimeException("远程服务调用失败");
            }
        }else {
            //无需解锁
        }
    }

    /**
     *  从订单交换机发过来的解锁库存的信息
     *  防止订单服务卡顿，导致订单状态一直改不了，库存的信息优先到期，从而导致库存无法解锁
     * @param
     */
    @Override
    public void unlockStock(OrderTo orderTo) {
        System.out.println("************从订单模块收到库存解锁的消息********************");
        //为防止重复解锁，需要重新查询工作单
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity taskEntity=orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = taskEntity.getId();
        List<WareOrderTaskDetailEntity> lockDetails = orderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", id)
                        .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity lockDetail : lockDetails) {
            unLockStock(lockDetail.getSkuId(),lockDetail.getWareId(),lockDetail.getSkuNum(),lockDetail.getId());
        }

    }

    //解锁库存
    public void unLockStock(Long skuId,Long wareId, Integer num,Long taskDeailId){
        wareSkuDao.unLockStock(skuId,wareId,num);
        // 更新库存工作单的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        //根据id来修改，唯一性
        detailEntity.setId(taskDeailId);
        detailEntity.setLockStatus(2); //已解锁
        orderTaskDetailService.updateById(detailEntity);
    }

    @Data
    class SkuWareHasStock{
        private long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}
